import React from 'react';
import {Typography, Form, Input, Radio, Select, Button, Space, Modal, InputNumber, message} from "antd"
import {CloseCircleOutlined, PlusOutlined} from '@ant-design/icons';
import GoBack from "@/components/TheGoBack";
import TheUpload from '@/components/TheUpload'
import {apiActivityLinkList} from "@/request/h5"
import List from "../../shuffling/component/carousellist"
import {apiInsertOrUpdate, apiPopupView} from "@/request/homePopup/index"

const {Title} = Typography;
const {Option} = Select
const formItemLayoutWithOutLabel = {
    wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 20, offset: 2},
    },
};

export default class Add extends React.Component {
    constructor() {
        super();
        this.state = {
            title: '', // 页面title
            id: '', // 弹窗id
            initialValues: {
                popUpType: 1, // 弹窗类型
                popUpFrequency: 0, // 弹窗频次
                targetedCrowdsType: 0, // 定向人群
                showAddressType: 0, // 展示位置
                // linkUrl: null,// 选择链接
                activeList: [], // 选择链接
                floatingWindows: 1, // 关闭收为浮窗
                whetherDirectAccess: 'N',
                floatingWindowImage: '', //浮窗图片
            },
            showAddressType: 0,//展示位置
            radioValue: '', // 跳转链接选择
            params: [], // 参数
            popUpImageList: [], // 弹窗图片回显
            linkUrl: '',// 选择链接
            visible: false, // 选择对应外链的弹窗
            typeTitle: '', // 选择对应外链的弹窗标题
            btnLoading: false, // 弹窗确定按钮loading
            floatingImgFileList: [], // 浮窗图片回显
            floatingWindows: null, // 关闭收为浮窗
            whetherDirectAccess: 'N',
            text: '', // 回显内容
        }
    }

    componentDidMount = async () => {
        let {type, id} = this.props.match.params
        this.setState({title: type, id: id})
        await this.getActiveList()  // 外部链接
        if (id !== 'null') {
            await this.getView(id)
        }
    }
    // 首页弹框数据回显
    getView = async (id) => {
        let res = await apiPopupView({id})
        if (res.code === 0) {
            if (res.data.jumpLink === 1) {
                let users = []
                let url = []
                if (res.data.linkUrl.indexOf('?') != '-1') {
                    url = res.data.linkUrl.split('?')
                    res.data.linkUrl = url[0]
                    users = url[1].split('&')
                    let str = ''
                    users.map((item) => {
                        str = item.split('=')
                        this.state.params.push({
                            key: str[0],
                            value: str[1]
                        })
                    })
                } else {
                    res.data.linkUrl = res.data.linkUrl.trim()
                }
            }
            this.setState({
                showAddressType: res.data.popUpType,
                popUpImageList: res.data.popUpImage ? [{uid: '-1', name: 'image.png', url: res.data.popUpImage}] : [],
                floatingImgFileList: res.data.floatingWindowImage ? [{
                    uid: '-1',
                    name: 'image.png',
                    url: res.data.floatingWindowImage
                }] : [],
                radioValue: String(res.data.jumpLink),
                linkUrl: res.data.linkUrl,
                floatingWindows: res.data.floatingWindows,
                whetherDirectAccess: res.data.whetherDirectAccess,
                text: res.data
            })
            this.formRef.setFieldsValue({...res.data})
        }
    }
    // 图片回显
    getFileResult = (file) => {
        let popUpImage = file.map((v) => {
            if (v.response) {
                if (v.response.code === 0 && v.response.data) {
                    return v.response.data
                }
            }
        }).join(',')
        this.formRef.setFieldsValue({popUpImage})
    }
    // 浮窗图片回显
    getFloatingFileResult = (file) => {
        let floatingWindowImage = file.map((v) => {
            if (v.response) {
                if (v.response.code === 0 && v.response.data) {
                    return v.response.data
                }
            }
        }).join(',')
        this.formRef.setFieldsValue({floatingWindowImage})
    }

    // 外链地址下拉内容
    async getActiveList() {
        await apiActivityLinkList().then(res => {
            if (res.code === 0) {
                this.setState({
                    activeList: res.data
                })
            }
        })
    }

    // 跳转链接修改值
    radioChange = (e) => {
        this.setState({
            linkUrl: '',
            radioValue: String(e.target.value),
        }, () => {
            this.formRef.setFieldsValue({linkUrl: '', params: ''})
            const type = String(e.target.value)
            if (type !== '1') {
                this.openModal(type)
            } else {
                this.setState({linkUrl: '', params: ''})
            }
        })
    }
    // 选择对应的外链弹窗
    openModal = (CarouselType) => {
        switch (CarouselType) {
            case '3':
                this.setState({
                    visible: true,
                    typeTitle: '商城商品'
                })
                break;
            case '4':
                this.setState({
                    visible: true,
                    typeTitle: '线下门店'
                })
                break;
            case '5':
                this.setState({
                    visible: true,
                    typeTitle: '线下商品'
                })
                break;
            case '14':
                this.setState({
                    visible: true,
                    typeTitle: '宠物酒店'
                })
                break;
            case '15':
                this.setState({
                    visible: true,
                    typeTitle: '宠物医院'
                })
                break;
            case '16':
                this.setState({
                    visible: true,
                    typeTitle: '洗护美容'
                })
                break;
        }
    }
    // 关闭外链弹窗
    onCancel = () => {
        this.setState({visible: false})
    }
    // 确定选择外链弹窗内容
    onOk = () => {
        this.setState({visible: false})
    }

    // 选择对应的选择链接
    getStringName(carouselUri, type) {
        let str = ''
        if (type !== '1') {
            if (carouselUri !== '') {
                carouselUri = JSON.parse(carouselUri)
                switch (type) {
                    case '2':
                        str = carouselUri.storeName
                        break;
                    case '3':
                        str = carouselUri.goodsName + carouselUri.storeName
                        break;
                    case '4':
                    case '14':
                    case '15':
                    case '16':
                        str = carouselUri.storeName
                        break;
                    case '5':
                        str = carouselUri.productName + carouselUri.storeName
                        break;
                    case '6':
                        str = carouselUri.serviceName + carouselUri.storeName
                        break;
                    case '7':
                        str = ''
                        break;
                    case '8':
                        str = ''
                        break;
                    case '9':
                        str = carouselUri.serviceClassifyName
                        break;
                    case '10':
                        str = ''
                        break;
                    case '11':
                        str = ''
                        break;
                    case '12':
                        str = ""
                        break;
                    case '13':
                        str = ""
                        break;
                    default:
                        break;
                }
            }
        }
        return str
    }

    // 选择弹框中的对应选择的链接
    goDetail(param) {
        let {type, typeId, typeName, storeId, storeName} = param;
        switch (type) {
            case '3':
                // 商城商品
                const goodsObj = {goodsId: typeId, goodsName: typeName, storeId: storeId, storeName: storeName}
                const goodsCarouselUri = JSON.stringify(goodsObj);
                this.setState({
                    visible: false,
                    linkUrl: goodsCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({linkUrl: `${typeName},${storeName}`})
                })
                break;
            // 线下门店
            case '4':
                const storeObj = {storeId: typeId, storeName: typeName}
                const storeCarouselUri = JSON.stringify(storeObj);
                this.setState({
                    visible: false,
                    linkUrl: storeCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({linkUrl: typeName})
                })
                break;
            // 线下商品
            case '5':
                const productObj = {productId: typeId, productName: typeName, storeId: storeId, storeName: storeName}
                const productCarouselUri = JSON.stringify(productObj);
                this.setState({
                    visible: false,
                    linkUrl: productCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({linkUrl: `${typeName},${storeName}`})
                })
                break;
            // 宠物酒店
            case '14':
                const hotelObj = {storeId: typeId, storeName: typeName, type: 'HOTEL'}
                const hotelUri = JSON.stringify(hotelObj);
                this.setState({
                    visible: false,
                    linkUrl: hotelUri
                }, () => {
                    this.formRef.setFieldsValue({linkUrl: typeName})
                })
                break;
            // 宠物医院
            case '15':
                const hospitalObj = {storeId: typeId, storeName: typeName, type: 'HOSPITAL'}
                const hospitalUri = JSON.stringify(hospitalObj);
                this.setState({
                    visible: false,
                    linkUrl: hospitalUri
                }, () => {
                    this.formRef.setFieldsValue({linkUrl: typeName})
                })
                break;
            // 洗护美容
            case '16':
                const hairdressobj = {storeId: typeId, storeName: typeName, type: "HAIRDRESSING"}
                const hairdressUri = JSON.stringify(hairdressobj);
                this.setState({
                    visible: false,
                    linkUrl: hairdressUri
                }, () => {
                    this.formRef.setFieldsValue({linkUrl: typeName})
                })
                break;
        }
    }

    // 选择链接选择地址链接时显示参数的参数值
    configCarouselUriChange = (e) => {
        this.formRef.setFieldsValue({params: ''})
        this.setState({linkUrl: e})
    }
    // 弹窗频次下拉框
    frequencyChange = (e) => {
        this.setState({popUpFrequency: e})
    }
    // 定向人群下拉框
    targetedCrowdsTypeChange = (e) => {
        this.setState({targetedCrowdsType: e})
    }
    // 展示位置
    showAddress = (e) => {
        this.setState({showAddressType: e})
    }
    // 是否关闭浮窗
    floatingWindowsChange = (e) => {
        this.setState({floatingWindows: e.target.value})
    }
    whetherDirectAccessChange = (e) => {
        this.setState({whetherDirectAccess: e.target.value})
    }
    // 表单确定提交
    onFinish = async (value) => {
        console.log(value)
        this.setState({btnLoading: true})
        if (this.state.radioValue !== '1') {
            value.linkUrl = this.state.linkUrl
        } else {
            value.linkUrl = value.linkUrl.trim()
        }
        let str = ''
        if (value.params && value.params.length !== 0) {
            value.params.map((item, index) => {
                str += item.key + '=' + item.value
                if (index + 1 !== value.params.length) {
                    str += '&'
                }
                return str
            })
            value.linkUrl = value.linkUrl.trim() + '?' + str
            delete value.params
        }

        if (value.popUpFrequency === 0) {
            value.popUpFrequency = '每天1次，每人最多3次'
        }
        if (value.popUpType === 3){
            value.popUpFrequency = '首次使用红包、转账、宠币赠送时弹出'
        }
        if (this.state.id !== 'null' && this.state.id) {
            let res = await apiInsertOrUpdate({...value, id: this.state.id})
            if (res.code === 0) {
                message.success('修改成功！')
                this.props.history.goBack()
            }
        } else {
            let res = await apiInsertOrUpdate({...value})
            if (res.code === 0) {
                message.success('新建成功！');
                this.props.history.goBack()
            }
        }
        this.setState({btnLoading: false})
    }
    RadioTypes = (showAddressType) => {
        this.setState({
            showAddressType
        })
    }
    onValuesChange = (changedValues, allValues) => {
        // 商品范围 优惠叠加交互
        if ('popUpType' in changedValues) {
            if (changedValues.popUpType === 3) {
                this.formRef.setFieldsValue({ targetedCrowdsType: 0 })
            }
        }
    }
    render() {
        let {
            title,
            initialValues,
            popUpImageList,
            showAddressType,
            whetherDirectAccess,
            id,
            activeList,
            radioValue,
            linkUrl,
            params,
            typeTitle,
            visible,
            btnLoading,
            floatingImgFileList,
            floatingWindows,
            text
        } = this.state
        let str = ""
        let options = {}
        let disabled = false
        switch (title) {
            case 'editNumansPopup':
                str = '新人系统弹窗'
                options = {value: 0, label: '仅1次'}
                break
            case 'editCouponPopup':
                str = '优惠券弹窗'
                options = {value: 0, label: '自定义，每天最多1次'}
                break
            case 'editActivePopup':
                str = '修改活动弹窗'
                options = {value: 0, label: '每天1次，每人最多3次'}
                break
            case 'viewPopup':
                str = '查看详情'
                disabled = true
                break
            default:
                str = '新建活动弹窗'
                options = {value: 0, label: '每天1次，每人最多3次'}
        }
        return (
            <div className="commodity-list-detail p-layout-box">
                <GoBack history={this.props.history} title={str}/>
                <Form onFinish={this.onFinish}
                      ref={ref => this.formRef = ref}
                      labelCol={{
                          span: 2,
                      }}
                      wrapperCol={{
                          span: 20,
                      }}
                      onFinishFailed={this.onFinishFailed}
                      onValuesChange={this.onValuesChange}
                      initialValues={initialValues}
                >
                    <Title level={5} style={{margin: "10px 0 10px 40px"}}>基础设置</Title>
                    <Form.Item rules={[{required: true}]} label="弹窗名称" name="popUpName">
                        <Input style={{width: 300}} maxLength={15} disabled={title !== 'addActivePopup'}/>
                    </Form.Item>
                    <Form.Item rules={[{required: true}]} name='popUpType' label='展示位置'>
                        <Select style={{width: 300}} onChange={(e) => this.RadioTypes(e)}
                                disabled={title !== 'addActivePopup'}
                                options={[
                                    {
                                        value: 0,
                                        label: '系统',
                                        disabled: title === 'addActivePopup' || title === 'editActivePopup'
                                    },
                                    {value: 1, label: '活动'},
                                    {value: 2, label: '口袋'},
                                    {value: 3, label: '风控'},
                                ]}></Select>
                    </Form.Item>
                    {/* <Form.Item rules={[{ required: true }]} label="弹窗类型" name="popUpType">
            <Radio.Group disabled={title !== 'addActivePopup'} onChange={(e) => this.RadioTypes(e)}>
              <Radio value={0} disabled={title === 'addActivePopup' || title === 'editActivePopup'}>系统</Radio>
              <Radio value={1}>活动</Radio>
              <Radio value={2}>口袋</Radio>
            </Radio.Group>
          </Form.Item> */}
                    <Form.Item name="popUpImage" label='弹窗图片'
                               rules={[{required: title === 'editCouponPopup' || text.popUpName === '优惠券到账/到期提醒' ? false : true}]}>
                        {title === 'editCouponPopup' || text.popUpName === '优惠券到账/到期提醒' ? "无" :
                            <TheUpload len={1} fileList={popUpImageList} getFileResult={this.getFileResult}
                                       isShowRemoveIcon={title !== 'viewPopup'}/>}
                    </Form.Item>
                    <Form.Item rules={[{required: true, message: '请选择跳转链接'}]} name='jumpLink' label='跳转链接'>
                        <Radio.Group onChange={this.radioChange} initialValues={radioValue} buttonStyle="solid"
                                     optionType='button'
                                     disabled={title === 'editCouponPopup' || title === 'viewPopup'}>
                            <Radio onClick={this.radioChange} value={1}>地址链接</Radio>
                            <Radio onClick={this.radioChange} value={3}>商城商品</Radio>
                            <Radio onClick={this.radioChange} value={4}>线下门店</Radio>
                            <Radio onClick={this.radioChange} value={5}>线下商品</Radio>
                            <Radio onClick={this.radioChange} value={7}>邀请有礼</Radio>
                            <Radio onClick={this.radioChange} value={8}>砍一刀</Radio>
                            <Radio onClick={this.radioChange} value={10}>我的卡包</Radio>
                            <Radio onClick={this.radioChange} value={11}>宠物出行</Radio>
                            <Radio onClick={this.radioChange} value={13}>宠物打车</Radio>
                            <Radio onClick={this.radioChange} value={14}>宠物酒店</Radio>
                            <Radio onClick={this.radioChange} value={15}>宠物医院</Radio>
                            <Radio onClick={this.radioChange} value={16}>洗护美容</Radio>
                            <Radio onClick={this.radioChange} value={20}>领券中心</Radio>
                            <Radio onClick={this.radioChange} value={24}>拼团频道</Radio>
                            <Radio onClick={this.radioChange} value={26}>秒杀频道</Radio>
                            <Radio onClick={this.radioChange} value={30}>幸运抽奖</Radio>
                        </Radio.Group>
                    </Form.Item>
                    {radioValue === '' ? <Form.Item
                            name='linkUrl'
                            label='链接地址'>
                            <Input style={{width: 300}}/>
                        </Form.Item> :
                        (radioValue === '7' || radioValue === '8' || radioValue === '10' || radioValue === '11' || radioValue === '12' || radioValue === '13' || radioValue === '20' || radioValue === '24' || radioValue === '26' || radioValue === '30') ?
                            <Form.Item name='linkUrl'
                                       label='选择链接'>
                                <Input readOnly placeholder="无需填写" style={{width: 300}}
                                       disabled={title === "viewPopup"}/>
                            </Form.Item> :
                            <Form.Item name='linkUrl'
                                       label='选择链接'
                                       rules={[{required: radioValue !== '1' ? true : false, message: '请选择链接'}]}
                            >
                                {radioValue === '1' ?
                                    <Select onChange={this.configCarouselUriChange} style={{width: 300}}
                                            disabled={title === 'viewPopup'}>
                                        {
                                            activeList.map(item => <Option value={item.activityLink}
                                                                           key={item.id}>{item.activityName}</Option>)
                                        }

                                    </Select> : <div style={{
                                        border: title !== 'viewPopup' ? '1px solid #ccc' : 'none',
                                        lineHeight: '28px',
                                        paddingLeft: '10px',
                                        minHeight: '30px'
                                    }}>
                                        {
                                            this.getStringName(linkUrl, radioValue)
                                        }
                                    </div>}
                            </Form.Item>
                    }
                    {
                        radioValue === '1' && linkUrl !== null ? <Form.List name="params" initialValue={params}>
                            {(fields, {add, remove}) => (
                                <>
                                    <Form.Item label="参数">
                                        <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined/>}
                                                style={{width: 300}} disabled={title === 'viewPopup'}>
                                            添加参数
                                        </Button>
                                    </Form.Item>
                                    {fields.map(({key, name, ...restField}) => (
                                        <Form.Item
                                            {...formItemLayoutWithOutLabel}
                                            required={false}
                                            key={key}
                                            style={{
                                                margin: 0
                                            }}
                                        >
                                            <Space
                                                style={{
                                                    display: 'flex',
                                                    marginBottom: 0,
                                                }}
                                                align="baseline"
                                            >
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'key']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请输入参数名',
                                                        },
                                                    ]}

                                                >
                                                    <Input placeholder="参数名" disabled={title === 'viewPopup'}/>
                                                </Form.Item>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'value']}
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请输入参数值',
                                                        },
                                                    ]}
                                                >
                                                    <Input placeholder="参数值" disabled={title === 'viewPopup'}/>
                                                </Form.Item>
                                                {title === 'viewPopup' ? null :
                                                    <CloseCircleOutlined onClick={() => remove(name)}/>}
                                            </Space>
                                        </Form.Item>
                                    ))}
                                </>
                            )}
                        </Form.List> : ''
                    }
                    <Title level={5} style={{margin: "50px 0 10px 40px"}}>其他设置</Title>
                    <Form.Item name='popUpFrequency' label='弹窗频次'>
                        {
                            showAddressType === 3 ? <Select style={{width: 300}} disabled={title !== 'addActivePopup'}
                                                            onChange={this.frequencyChange}
                                                            options={[{
                                    value: 0,
                                    label: '首次使用红包、转账、宠币赠送时弹出'
                                }]}></Select> :
                                <Select style={{width: 300}} disabled={title !== 'addActivePopup'}
                                        onChange={this.frequencyChange}
                                        options={[options]}></Select>
                        }
                    </Form.Item>
                    {[0, 1].includes(showAddressType) &&
                        <Form.Item rules={[{required: true}]} name='priority' label='优先级'
                                   extra={title === 'editCouponPopup' ? '（说明：新人弹窗和优惠券到账/到期提醒弹窗目前存在互斥关系，当天仅会弹一次新人弹窗）' : ''}>
                            <InputNumber style={{width: 300}} precision={0} disabled={title === 'viewPopup'}/>
                        </Form.Item>}
                    <Form.Item name='targetedCrowdsType' label='定向人群'>
                        <Select style={{width: 300}} disabled={title !== 'addActivePopup' || showAddressType === 3}
                                onChange={this.targetedCrowdsTypeChange}
                                options={[
                                    {value: 0, label: '全部用户可见'},
                                    {value: 1, label: '仅新用户可见'}
                                ]}></Select>
                    </Form.Item>
                    {[0, 1].includes(showAddressType) && <Form.Item name='floatingWindows' label='关闭收为浮窗'>
                        <Radio.Group
                            disabled={title === 'viewPopup' || title === 'editCouponPopup' || title === 'editNumansPopup'}>
                            <Radio onClick={(e) => this.floatingWindowsChange(e)} value={0}>是</Radio>
                            <Radio onClick={(e) => this.floatingWindowsChange(e)} value={1}>否</Radio>
                        </Radio.Group>
                    </Form.Item>}
                    {
                        (title === 'editNumansPopup'
                            || title === 'viewPopup') && id == 1 &&
                        <Form.Item name='whetherDirectAccess' label='是否直接打开h5'>
                            <Radio.Group disabled={title === 'viewPopup'}>
                                <Radio onClick={(e) => this.whetherDirectAccessChange(e)} value='Y'>是</Radio>
                                <Radio onClick={(e) => this.whetherDirectAccessChange(e)} value="N">否</Radio>
                            </Radio.Group>
                        </Form.Item>
                    }

                    {[0, 1].includes(showAddressType) && <Form.Item name="floatingWindowImage" label='浮窗图片'
                                                                    rules={[{required: floatingWindows == 0}]}>
                        {floatingWindows == 0 ?
                            <TheUpload len={1} fileList={floatingImgFileList} getFileResult={this.getFloatingFileResult}
                                       isShowRemoveIcon={title !== 'viewPopup'}/> : '无'}
                    </Form.Item>}

                    <Modal
                        visible={visible}
                        onCancel={this.onCancel}
                        title={typeTitle}
                        width='1000px'
                        destroyOnClose={true}
                        footer={null}
                    >
                        <List radiotype={String(radioValue)} getList={(e) => this.goDetail(e)}/>
                    </Modal>
                    {
                        title === 'viewPopup' ? null : <div className="p-text-align">
                            <Space size="large">
                                <Button key="back" onClick={() => this.props.history.goBack()}>
                                    取 消
                                </Button>
                                <Button type="primary" loading={btnLoading} htmlType="primary">
                                    确 定
                                </Button>
                            </Space>
                        </div>
                    }
                </Form>
            </div>
        )
    }
}
